package correiosDados;

import correios.AddressNotFoundException;
import correios.BadCEPException;
import correios.BadCEPInHTMLException;
import correios.CEPNotFoundException;

public class HTML {
	
	private String pagina;
	
	public HTML(String pagina){		
		this.setPagina(pagina);
	}
	
	public void setPagina(String pagina) {
		this.pagina = pagina;
	}
	
	public CEP parseForCEP() throws CEPNotFoundException, BadCEPInHTMLException{
		String[] chunkedContent;
		CEP cep;
		int i;
		
		chunkedContent = pagina.split("<table");
		for(i = 0; i < chunkedContent.length; i++){
			if(chunkedContent[i].contains("border=\"0\" cellspacing=\"1\" cellpadding=\"5\" bgcolor=\"gray\"")){
				break;
			}
		}
		
		if(i == chunkedContent.length){
			throw new CEPNotFoundException();
		}
		
		chunkedContent = chunkedContent[i].split("<td ");
		chunkedContent = chunkedContent[5].split("</td>");
		chunkedContent = chunkedContent[0].split("\">");
		
		try {
			cep = new CEP(chunkedContent[chunkedContent.length - 1]);
		} catch (BadCEPException e) {
			throw new BadCEPInHTMLException();
		}
		
		return cep;
		
	}
	
	public Endereco parseForEndereco() throws AddressNotFoundException{
		String[] chunkedContent;
		Endereco endereco;
		String aux, ret;
		int i;
		
		chunkedContent = pagina.split("<table");
		for(i = 0; i < chunkedContent.length; i++){
			if(chunkedContent[i].contains("border=\"0\" cellspacing=\"1\" cellpadding=\"5\" bgcolor=\"gray\"")){
				break;
			}
		}
		
		if(i == chunkedContent.length){
			throw new AddressNotFoundException();
		}
		
		ret = new String();
		
		chunkedContent = chunkedContent[i].split("<td ");
		
		for(i = 1; i < 5; i++){
			aux = chunkedContent[i];
			aux = aux.split("</td>")[0].split("\">")[1];
			ret = ret.concat(aux);
			if(i != 4){
				ret = ret.concat(", ");
			}
		}

		endereco = new Endereco(ret);
		
		return endereco;
	}
	
	
}
